package com.zygk.xmpp.dao;

import android.content.Context;
import com.yanzhenjie.nohttp.FileBinary;
import com.yanzhenjie.nohttp.RequestMethod;
import com.yanzhenjie.nohttp.rest.Response;
import com.yanzhenjie.nohttp.rest.SimpleResponseListener;
import com.yanzhenjie.nohttp.rest.StringRequest;
import com.zygk.library.util.CallServer;
import com.zygk.library.util.JsonUtil;
import com.zygk.library.util.PreferencesHelper;
import com.zygk.library.util.ToastUtil;
import com.zygk.xmpp.constant.Urls;
import com.zygk.xmpp.model.apimodel.APIM_uploadFile;
import com.zygk.xmpp.util.HttpRequest;
import java.io.File;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by Administrator on 2018/7/31 0031.
 */

public class UploadLogic {
  /**
   * 上传视频、图片
   */
  public static void upload(final Context context, String path,String url,
      final HttpRequest.HttpCallback callback) {
    File newFile = new File(path);
    StringRequest request =
        new StringRequest(Urls.BASE_URL + url, RequestMethod.POST);
    request.add("filename", new FileBinary(newFile));

    SimpleResponseListener<String> listener = new SimpleResponseListener<String>() {
      @Override public void onStart(int what) {
        super.onStart(what);
        callback.onStart();
      }

      @Override public void onSucceed(int what, Response<String> response) {
        super.onSucceed(what, response);
        APIM_uploadFile result = JsonUtil.jsonToObject(response.get(), APIM_uploadFile.class);

        if (result == null) return;

        if (result.getStatus() == 100) {
          callback.onSucceed(result);
        } else {
          ToastUtil.showMessage(context, result.getMessage());
        }
      }

      @Override public void onFailed(int what, Response<String> response) {
        super.onFailed(what, response);
        callback.onFailed();
      }

      @Override public void onFinish(int what) {
        super.onFinish(what);
        callback.onFinish();
      }
    };
    CallServer.getInstance().request(0, request, listener);
  }
}
